from fastapi import APIRouter, Query

from fastapiApp.controllers.dept_control import dept_controller
from fastapiApp.schemas.base_scheams import Fail, Success, SuccessExtra
from fastapiApp.schemas.dept_scheams import *

router = APIRouter()

@router.get("/get_list", summary="查看部门列表")
async def list_dept(
    name: str = Query(None, description="部门名称")
):
    dept_tree = await dept_controller.get_dept_tree(name)
    return Success(data=dept_tree)

@router.get("/get_info", summary="查看部门")
async def get_dept(
    id: int = Query(..., description="部门ID")
):
    dept_obj = await dept_controller.model.get(id=id)
    data = await dept_obj.to_dict()
    return Success(data=data)

@router.post("/create", summary="创建部门")
async def create_dept(
    obj_in: DeptCreate
):
    await dept_controller.is_exist(obj_in = obj_in)
    await dept_controller.model.create(** obj_in.model_dump())
    return Success(msg="Created Successfully")

@router.post("/update", summary="更新部门")
async def update_dept(
    obj_in: DeptUpdate
):
    await dept_controller.update_dept(obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")

@router.delete("/delete", summary="删除部门")
async def delete_dept(
    id: int = Query(..., description="部门ID")
):
    dept = await dept_controller.model.get_or_none(id = id)
    if dept:
        await dept.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")
